import datetime
import random
import sys
import time

from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By

from libs import config
from libs.action import WebDriverAction
from libs.game import Game
from libs.image import ImageTool
from libs.log import Log
from libs.movement import Movement, KeyCode
from libs.task_helper import TaskHelper
from libs.trade_helper import TradeHelper
from libs.window import AdsWindow


def craft(x, y, item_name, collect_after=None):
    for _ in range(2):
        try:
            action.click_by_offset(x, y)
            time.sleep(1)
            title = action.find_element(By.XPATH,
                                        f"//div[@class='Crafting_detailsTitle__bGjKU']//div[1]",
                                        'Title', 3)
            if title is None or title.text != item_name:
                back_button = action.find_element(By.XPATH, f"//button[text()='Back']", 'BackButton', 1)
                if back_button:
                    back_button.click()
                    time.sleep(1)
                opt = action.find_element(By.XPATH,
                                          f"//div[@class='Crafting_craftingRecipeItem__vnhBH']//span[text()='{item_name}']",
                                          item_name, 3)
                if opt is None:
                    action.escape()
                    time.sleep(1)
                    action.click()
                    opt = action.find_element(By.XPATH,
                                              f"//div[@class='Crafting_craftingRecipeItem__vnhBH']//span[text()='{item_name}']",
                                              item_name, 3)
                opt.click()
                break
        except:
            action.escape()
            action.escape()
            time.sleep(3)
    time.sleep(1)
    craft_count = 0
    for _ in range(5):
        craft_button = action.find_element(By.CLASS_NAME, "Crafting_craftingButton__Qd6Ke", 'CraftButton', 2)
        if craft_button is None:
            action.escape()
            action.click_by_offset(x, y)
            time.sleep(1)
            log.debug('no craft button')
            continue
        if craft_button.text == 'Collect':
            if craft_button.is_enabled():
                craft_button.click()
                time.sleep(1)
                continue
        if craft_button.text == 'Create':
            if craft_button.is_enabled():
                craft_button.click()
                time.sleep(random.randint(1, 2))
                craft_count = 1
            break
        time.sleep(1)
    if craft_count > 0 and collect_after is not None:
        time.sleep(collect_after)
        for _ in range(5):
            craft_button = action.find_element(By.CLASS_NAME, "Crafting_craftingButton__Qd6Ke", 'CraftButton', 2)
            if craft_button.text == 'Collect':
                if craft_button.is_enabled():
                    craft_button.click()
                    time.sleep(1)
                    break
            time.sleep(1)
    return craft_count


def cut_tree(x, y, cut_time):
    global current_x, current_y
    ac.move_by_offset(x - current_x, y - current_y).perform()
    current_x = x
    current_y = y
    for _ in range(cut_time):
        ac.click().perform()
        time.sleep(random.randint(3, 4) / 10)


if __name__ == "__main__":
    parser = TaskHelper.default_args_parser('ForestAndWood')
    parser.add_argument('--mode', type=int, help="运行模式", required=False)
    args = parser.parse_args()
    task_helper = TaskHelper.from_args(args)

    user_id = args.user_id
    log = Log(user_id)

    try:
        driver = AdsWindow(user_id).open(False)
        game = Game(driver, user_id)
        action = WebDriverAction(driver, user_id=user_id)
        movement = Movement(driver)
        image_tool = ImageTool(driver)
        trade_helper = TradeHelper(driver, user_id)
        ac = ActionChains(driver)
        log_name = 'Whittlewood Log'

        game.enter_game()
        game.collect_mail()
        snapshot = game.snapshot(user_id, 'before forest_and_wood')
        skills = snapshot.get('skills')
        forest_skill = skills.get('forestry')
        wood_skill = skills.get('wood', 0)
        log_qty = game.get_backpack_qty(log_name)

        log.info(f'before: forestry={forest_skill}, wood={wood_skill}, log_qty={log_qty}')

        axe_qty = game.get_backpack_qty('Basic Axe')
        if axe_qty < 2 and game.get_coin() > 30:
            # 买斧头/买酒
            action.goto_spec()
            trade_helper.goto_seed_store()
            trade_helper.open_seed_buy()
            trade_helper.buy_seed('Basic Axe', 2 - axe_qty)

            action.escape()
            action.escape()

        # 砍树
        home_loc = action.goto_spec()
        home_x, home_y = home_loc
        game.drink_wine(600, home_x + 45, home_y + 180)

        movement.keep_move_up(1.5)
        movement.keep_move_left(1)
        movement.keep_move_down(0.5)
        movement.keep_move_left(4)
        movement.keep_move_up(1)
        axe_image = 'axe_lv1.png'

        current_x = 0
        current_y = 0
        for _ in range(10):
            game.open_backpack()
            axe_loc = image_tool.find_nearest_target(axe_image, near_x=0, near_y=0)
            if axe_loc is None:
                log.debug('no_axe')
                break
            axe_x, axe_y = axe_loc
            action.click_by_offset(axe_x + 10, axe_y + 10)
            game.close_backpack()
            if game.get_energy() < 100:
                log.debug('energy_not_enough')
                break
            time.sleep(0.5)
            region = (100, 300, 500, 750)
            tree_locs = image_tool.find_all_targets('tree_v1.png', region)
            root_locs = image_tool.find_all_targets('tree_root_v1.png', region)
            ac.reset_actions()
            ac.move_by_offset(current_x, current_y).perform()
            if len(root_locs) + len(tree_locs) == 0:
                log.debug('nothing_to_cut')
                break
            for x, y in tree_locs:
                x += 13
                y += 23
                cut_tree(x, y, 20)
            for x, y in root_locs:
                y += 15
                cut_tree(x, y, 15)
            action.escape()
            movement.keep_move_up(0.5)
            movement.keep_move_down(0.4)
            movement.keep_move_right(1.3)
            movement.keep_move_left(1.5)
            movement.keep_move_up(0.6)
        action.escape()
        action.escape()

        try:
            game.get_backpack()
            log_qty = game.get_backpack_qty(log_name)
            log.debug(f'after_cut: log_qty={log_qty}')
            if log_qty >= 80 and game.get_energy() > 390:
                wood_workings = image_tool.find_all_targets('wood_working_v1.png', [50, 450, 350, 700])
                for (x, y) in wood_workings:
                    craft(x, y, 'Pile of Sawdust')
                    action.escape()
                movement.keep_move_right(2)
                movement.keep_move_down(1)
                wood_workings = image_tool.find_all_targets('wood_working_v1.png', [350, 350, 750, 900])
                for (x, y) in wood_workings:
                    craft(x, y, 'Pile of Sawdust')
                    action.escape()
        except Exception as e:
            print(e)
            pass

        snapshot = game.snapshot(user_id, 'before after_and_wood')
        skills = snapshot.get('skills')
        forest_skill = skills.get('forestry')
        wood_skill = skills.get('wood')
        log.info(f'after: forestry={forest_skill}, wood={wood_skill}')

        task_helper.task_success()

    except Exception as e:
        task_helper.task_fail()
        task_helper.add_task('forest_and_wood.py', delay_seconds=30 * 60, ignore_running=True, retry=True)
        raise e
